<template>
  <div class="login-container">
    <div class="logo">
      <img src="../assets/elmlogo.jpg" alt="logo">
    </div>
    <div class="form-box">
      <el-input 
        v-model="loginForm.userId" 
        placeholder="手机号"
        class="input-item"
      />
      <el-input 
        v-model="loginForm.password" 
        type="password"
        placeholder="密码"
        class="input-item"
        show-password
      />
      <el-button type="primary" @click="login" class="submit-btn">登录</el-button>
      
      <div class="register-link">
        <span>没有账号？</span>
        <el-link type="primary" @click="goToRegister">去注册</el-link>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import Footer from './Footer.vue'
import qs from 'qs'

const router = useRouter()

const loginForm = ref({
  userId: '',
  password: ''
})

// 登录
const login = async () => {
  try {
    // 表单验证
    if (!loginForm.value.userId) {
      ElMessage.warning('请输入手机号')
      return
    }
    if (!loginForm.value.password) {
      ElMessage.warning('请输入密码')
      return
    }

    // 发送登录请求
    const response = await request({
      url: '/UserController/login',
      method: 'post',
      data: {
        userId: loginForm.value.userId,
        password: loginForm.value.password
      }
    })

    if (response.data?.token) {
      // 保存用户信息和token
      sessionStorage.setItem('token', `Bearer ${response.data.token}`)
      sessionStorage.setItem('user', JSON.stringify(response.data.user))
      
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      ElMessage.error(response.data || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    if (error.response?.data) {
      ElMessage.error(error.response.data)
    } else if (error.response?.status === 403) {
      ElMessage.error('用户名或密码错误')
    } else {
      ElMessage.error('登录失败，请稍后重试')
    }
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: #fff;
  padding: 20px;
}

.logo {
  text-align: center;
  margin: 80px 0;
}

.logo img {
  width: 200px;
}

.form-box {
  padding: 0 20px;
}

.input-item {
  margin-bottom: 20px;
}

.input-item :deep(.el-input__inner) {
  height: 45px;
  border-radius: 25px;
  border: 1px solid #eee;
}

.submit-btn {
  width: 100%;
  height: 45px;
  border-radius: 25px;
  background: #00a7ff;
  font-size: 16px;
  margin-bottom: 15px;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #999;
}

.register-link :deep(.el-link--primary) {
  font-size: 14px;
  color: #00a7ff;
}
</style>